<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监听对象</title>
</head>
<body>
    <script>
        // //之前使用的方式，给对象的每一个值加上一个数据存储属性
        // let obj = {
        //     name:"cq",
        //     age:18,
        //     height:1.90
        // }
        // //遍历所有的key，给key添加上数据存储属性
        // let keys =  Object.keys(obj);
        // for(let key of keys)
        // {
        //     Object.defineProperty(obj,key,{
        //         set:function(value)
        //         {
        //             console.log(`${key}值发生改变，变为${value}`);
        //         },
        //         get:function()
        //         {
        //            console.log(`${key}值被获取`);
        //         }
        //     })
        // }
        // let name1 = obj.name;
        // obj.name = "cqcq";

        // //添加新属性后不能监听
        // obj.id = 12345;
         let obj = {
            name:"cq",
            age:18,
            height:1.90
        }
        
        //给obj设置代理对象实现监听
        const newProxy = new Proxy(obj,{
            set: function (target,key,newValue){
                  console.log(`给对象${target}的属性${key}设置新值${newValue}`);
            },
            
            get:function(target,key)
            {
                 console.log(`改变对象${target}的属性${key}`);
            },
            deleteProperty:function(target,key)
            {
                console.log(`删除${target}的属性${key}`);
            },
            has:function(target,key)
            {
                console.log(`${target}含有属性${key}`);
            }
        })
        console.log(newProxy.name);
        delete newProxy.name;
        delete newProxy.age;
        newProxy.id = 123456;

        function foo()
        {
             console.log(`函数被调用`);
             return "foo";
        }

        let newProxy2 = new Proxy(foo,{
            construct(target,thisArg,ortherArg)
            {
               console.log(`${target}，被${thisArg}调用，传入的参数是${ortherArg}`);
               return new target();
            },
            apply:function(target,thisArg,newtarget)
            {
                console.log(target,thisArg, newtarget);
                return target.apply(thisArg,ortherArg);
            }
        })
      

        let foo2 = new newProxy2;
        
      
    </script>
</body>
</html>